import react from '@vitejs/plugin-react'
import dayjs from 'dayjs'
import path from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
import { defineConfig, loadEnv } from 'vite'
import prefetchPlugin from 'vite-plugin-bundle-prefetch'
import svgr from 'vite-plugin-svgr'

const joinDir = (relativePath: string) => path.join(__dirname, relativePath)

// https://cn.vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  const isDev = command === 'serve'
  const env = loadEnv(mode, __dirname, ['BASE_URL', 'VITE_', 'M_DEV_'])

  if (!env.BASE_URL.endsWith('/')) {
    throw new Error('BASE_URL 变量要带尾杠')
  }
  if (env.VITE_APP_BASE_NAME.endsWith('/')) {
    throw new Error('VITE_APP_BASE_NAME 变量不要带尾杠')
  }
  if (!/^(local|staging|prod)$/.test(env.VITE_APP_ENV)) {
    throw new Error('VITE_APP_ENV 变量缺失或变量值不正确')
  }

  return {
    base: env.BASE_URL,
    plugins: [
      react(),
      svgr({ include: '**/*.svg?react' }), // https://github.com/pd4d10/vite-plugin-svgr
      prefetchPlugin({ excludeFn: v => v.includes('/omsHtml-') || v.includes('/tmsHtml-') || v.endsWith('.html') }),
      {
        name: 'html-transform',
        transformIndexHtml: h => `${h}<!-- ${dayjs().format('YYYY-MM-DD HH:mm')} -->\n`,
      },
      !isDev && env.M_DEV_VIS === 'true' && visualizer({ open: true, template: 'treemap' }),
    ],
    resolve: {
      alias: [
        {
          find: '@axiosMock',
          replacement: joinDir(`./src/services/axiosMock/axiosMock.${isDev ? 'dev' : 'prod'}.ts`),
        },
        { find: '@oBiz', replacement: joinDir('./src/pOTB/Biz') },
        { find: '@', replacement: joinDir('./src') },
        ...(!isDev || env.M_DEV_MOCK !== 'true'
          ? [
              {
                find: /.*\/__mock__(\/index)?(\.(js|jsx|ts|tsx|cjs))?$/,
                replacement: joinDir(`./src/services/axiosMock/__mock__.prod.ts`),
              },
            ]
          : []),
      ],
    },
    css: { devSourcemap: true },
    build: {
      outDir: env.VITE_APP_ENV === 'prod' ? 'dist/prod' : 'dist/staging',
      sourcemap: env.VITE_APP_ENV === 'staging',
      manifest: true,
      cssCodeSplit: false, // 所有样式合一起
      rollupOptions: {
        input: { omsHtml: joinDir('./entry/oms/index.html'), tmsHtml: joinDir('./entry/tms/index.html') },
        output: {
          // 有新包加入时请合理配置
          manualChunks: {
            'v-react': ['react', 'react-dom', 'react-router', 'react-router-dom'],
            'v-utils': [
              'ahooks',
              'immer',
              'zustand',
              'axios',
              'lodash',
              'dayjs',
              'dayjs/locale/zh-cn',
              'qs',
              'classnames',
              'bignumber.js',
              'md5',
              'copy-to-clipboard',
            ],
            'v-antd': ['antd', 'antd/locale/zh_CN'],
            'v-ag-grid': [
              '@ag-grid-community/client-side-row-model',
              '@ag-grid-community/core',
              '@ag-grid-community/locale',
              '@ag-grid-community/react',
              '@ag-grid-community/theming',
              '@ag-grid-enterprise/clipboard',
              '@ag-grid-enterprise/column-tool-panel',
              '@ag-grid-enterprise/menu',
              '@ag-grid-enterprise/range-selection',
              '@ag-grid-enterprise/status-bar',
            ],
          },
          experimentalMinChunkSize: 1024 * 5, // 小于该值且无副作用时不拆分，https://rollupjs.org/configuration-options/#output-experimentalminchunksize
          chunkFileNames: ({ name, moduleIds }) => {
            if (/^index(\.\w+)?$/i.test(name)) {
              const arr = moduleIds[moduleIds.length - 1].split('/')
              name = arr[arr.length - 2] // 使用目录名
            }
            return `assets/${name}-[hash].js`
          },
        },
      },
    },
    server: {
      host: '0.0.0.0',
      port: 8899,
      open: path.join('/', env.M_DEV_OPEN_PATH ?? ''),
      proxy: {
        [`/api/`]: {
          target: env.M_DEV_SERVICE_PROXY_OMS,
          changeOrigin: true,
        },
        [`/omsapi/`]: {
          target: env.M_DEV_SERVICE_PROXY_OMS,
          changeOrigin: true,
        },
        [`/tmsapi/`]: {
          target: env.M_DEV_SERVICE_PROXY_TMS,
          changeOrigin: true,
        },
      },
    },
  }
})
